#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
修复账户配置文件路径问题
统一使用绝对路径，确保账户配置文件和凭证文件保存在正确的位置
"""
import os
import sys
import json
import shutil

# 添加项目根目录到Python路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))


class SimpleLogger:
    """简单的日志类"""
    @staticmethod
    def info(msg):
        print(f"INFO: {msg}")
    
    @staticmethod
    def success(msg):
        print(f"✅ SUCCESS: {msg}")
    
    @staticmethod
    def warning(msg):
        print(f"⚠️ WARNING: {msg}")
    
    @staticmethod
    def error(msg):
        print(f"❌ ERROR: {msg}")


logger = SimpleLogger()


def fix_account_config_path():
    """修复账户配置文件路径问题"""
    logger.info("=== 开始修复账户配置文件路径问题 ===")
    
    # 获取项目根目录
    project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    logger.info(f"项目根目录: {project_root}")
    
    # 1. 定义正确的配置文件路径（与凭证文件路径保持一致）
    correct_config_dir = os.path.join(project_root, 'config')
    correct_config_path = os.path.join(correct_config_dir, 'accounts_config.json')
    logger.info(f"正确的配置文件路径: {correct_config_path}")
    
    # 2. 检查可能的错误配置文件位置
    # a) 项目根目录的上级目录下的config文件夹
    parent_dir = os.path.dirname(project_root)
    wrong_config_path1 = os.path.join(parent_dir, 'config', 'accounts_config.json')
    
    # b) 当前工作目录下的config文件夹
    wrong_config_path2 = os.path.join(os.getcwd(), 'config', 'accounts_config.json')
    
    # 3. 检查是否存在错误位置的配置文件
    found_wrong_config = False
    accounts_from_wrong_location = None
    
    # 检查第一个错误位置
    if os.path.exists(wrong_config_path1):
        logger.info(f"发现错误位置的配置文件: {wrong_config_path1}")
        try:
            with open(wrong_config_path1, 'r', encoding='utf-8') as f:
                wrong_config = json.load(f)
            accounts_from_wrong_location = wrong_config.get('accounts', {})
            if len(accounts_from_wrong_location) > 1 or ('default' not in accounts_from_wrong_location):
                found_wrong_config = True
                logger.info(f"发现用户添加的账户信息，共 {len(accounts_from_wrong_location)} 个账户")
        except Exception as e:
            logger.error(f"读取错误位置的配置文件失败: {str(e)}")
    
    # 检查第二个错误位置
    if not found_wrong_config and os.path.exists(wrong_config_path2):
        logger.info(f"发现错误位置的配置文件: {wrong_config_path2}")
        try:
            with open(wrong_config_path2, 'r', encoding='utf-8') as f:
                wrong_config = json.load(f)
            accounts_from_wrong_location = wrong_config.get('accounts', {})
            if len(accounts_from_wrong_location) > 1 or ('default' not in accounts_from_wrong_location):
                found_wrong_config = True
                logger.info(f"发现用户添加的账户信息，共 {len(accounts_from_wrong_location)} 个账户")
        except Exception as e:
            logger.error(f"读取错误位置的配置文件失败: {str(e)}")
    
    # 4. 创建正确的配置目录
    if not os.path.exists(correct_config_dir):
        logger.info(f"创建正确的配置目录: {correct_config_dir}")
        os.makedirs(correct_config_dir, exist_ok=True)
    
    # 5. 处理配置文件
    # 如果有正确位置的配置文件
    if os.path.exists(correct_config_path):
        logger.info(f"正确位置的配置文件已存在: {correct_config_path}")
        
        # 读取正确位置的配置文件
        try:
            with open(correct_config_path, 'r', encoding='utf-8') as f:
                correct_config = json.load(f)
            correct_accounts = correct_config.get('accounts', {})
        except Exception as e:
            logger.error(f"读取正确位置的配置文件失败: {str(e)}")
            correct_accounts = {'default': {
                'account_id': 'default',
                'platform': 'tencent',
                'account_name': '默认账户',
                'description': '系统默认账户'
            }}
        
        # 如果发现了错误位置的配置文件，合并账户信息
        if found_wrong_config and accounts_from_wrong_location:
            logger.info("合并错误位置的账户信息到正确位置...")
            # 保留正确位置的账户信息，添加错误位置的新账户
            for account_id, account_info in accounts_from_wrong_location.items():
                if account_id not in correct_accounts:
                    correct_accounts[account_id] = account_info
                    logger.success(f"添加账户: {account_info.get('account_name', account_id)}")
            
            # 更新配置
            correct_config['accounts'] = correct_accounts
            
            # 保存合并后的配置
            try:
                with open(correct_config_path, 'w', encoding='utf-8') as f:
                    json.dump(correct_config, f, ensure_ascii=False, indent=2)
                logger.success("成功保存合并后的配置文件")
            except Exception as e:
                logger.error(f"保存合并后的配置文件失败: {str(e)}")
    else:
        # 创建新的配置文件
        logger.info("创建新的配置文件...")
        
        # 如果发现了错误位置的配置文件，使用其中的账户信息
        if found_wrong_config and accounts_from_wrong_location:
            logger.info("使用错误位置的账户信息创建新配置文件")
            config = {
                'accounts': accounts_from_wrong_location,
                'active_account_id': next(iter(accounts_from_wrong_location.keys()))
            }
        else:
            # 创建默认配置
            logger.info("创建默认配置文件")
            default_account = {
                'account_id': 'default',
                'platform': 'tencent',
                'account_name': '默认账户',
                'description': '系统默认账户'
            }
            config = {
                'accounts': {'default': default_account},
                'active_account_id': 'default'
            }
        
        # 保存配置文件
        try:
            with open(correct_config_path, 'w', encoding='utf-8') as f:
                json.dump(config, f, ensure_ascii=False, indent=2)
            logger.success("成功创建新的配置文件")
        except Exception as e:
            logger.error(f"创建新的配置文件失败: {str(e)}")
    
    # 6. 创建修复后的账户管理器补丁
    patch_file_path = os.path.join(project_root, 'utils', 'account_manager_patched.py')
    logger.info(f"创建修复后的账户管理器补丁: {patch_file_path}")
    
    patch_content = """# -*- coding: utf-8 -*-
"""
账户管理器补丁 - 修复配置文件路径问题
"""
import json
import os
from typing import Dict, List, Optional, Tuple, Any
from utils.security_utils import secure_load_credentials, secure_save_credentials
from utils.exception_handler import handle_exception


class AccountManager:
    """
    账户管理器类，用于统一管理多个证券账户及其凭证
    """
    def __init__(self):
        """
        初始化账户管理器
        """
        # 存储所有账户信息 {account_id: account_info}
        self.accounts: Dict[str, Dict[str, Any]] = {}
        # 当前活跃账户ID
        self.active_account_id: Optional[str] = None
        # 账户配置文件路径 - 使用绝对路径，避免路径解析问题
        base_dir = os.path.dirname(os.path.abspath(__file__))
        base_dir = os.path.join(base_dir, '..')
        self.accounts_config_path = os.path.abspath(os.path.join(base_dir, 'config', 'accounts_config.json'))
        # 加载已保存的账户信息
        self.load_accounts()
        
    def load_accounts(self) -> None:
        """
        从配置文件加载所有账户信息
        """
        try:
            if os.path.exists(self.accounts_config_path):
                with open(self.accounts_config_path, 'r', encoding='utf-8') as f:
                    config = json.load(f)
                    self.accounts = config.get('accounts', {})
                    self.active_account_id = config.get('active_account_id')
                    # 确保活跃账户ID存在于账户列表中
                    if self.active_account_id and self.active_account_id not in self.accounts:
                        self.active_account_id = next(iter(self.accounts.keys()), None) if self.accounts else None
                
            # 初始化时，如果没有账户，创建一个默认账户
            if not self.accounts:
                default_account = {
                    'account_id': 'default',
                    'platform': 'tencent',
                    'account_name': '默认账户',
                    'description': '系统默认账户'
                }
                self.accounts[default_account['account_id']] = default_account
                self.active_account_id = default_account['account_id']
                self.save_accounts()
                
        except Exception as e:
            handle_exception(e, "加载账户配置失败")
    
    # 其他方法保持不变...
"""
    
    try:
        with open(patch_file_path, 'w', encoding='utf-8') as f:
            f.write(patch_content)
        logger.success("成功创建修复补丁")
    except Exception as e:
        logger.error(f"创建修复补丁失败: {str(e)}")
    
    # 7. 更新现有的account_manager.py文件
    account_manager_path = os.path.join(project_root, 'utils', 'account_manager.py')
    logger.info(f"更新现有的account_manager.py文件: {account_manager_path}")
    
    try:
        # 备份原文件
        backup_path = account_manager_path + '.backup'
        if os.path.exists(account_manager_path):
            shutil.copy2(account_manager_path, backup_path)
            logger.info(f"已备份原文件到: {backup_path}")
        
        # 读取原文件内容
        with open(account_manager_path, 'r', encoding='utf-8') as f:
            content = f.read()
        
        # 替换配置文件路径的初始化代码
        old_init_path = "self.accounts_config_path = os.path.join('config', 'accounts_config.json')"
        new_init_path = """# 账户配置文件路径 - 使用绝对路径，避免路径解析问题
        base_dir = os.path.dirname(os.path.abspath(__file__))
        base_dir = os.path.join(base_dir, '..')
        self.accounts_config_path = os.path.abspath(os.path.join(base_dir, 'config', 'accounts_config.json'))"""
        
        if old_init_path in content:
            updated_content = content.replace(old_init_path, new_init_path)
            
            # 保存更新后的文件
            with open(account_manager_path, 'w', encoding='utf-8') as f:
                f.write(updated_content)
            logger.success("成功更新account_manager.py文件，修复了路径问题")
        else:
            logger.warning("未找到需要替换的路径初始化代码，可能已经修复过")
    except Exception as e:
        logger.error(f"更新account_manager.py文件失败: {str(e)}")
    
    logger.info("=== 账户配置文件路径问题修复完成 ===")
    logger.success("🎉 修复已完成，请重新启动应用程序以查看效果")
    logger.info("💡 提示: 如果仍有账户显示问题，可以尝试在应用界面重新添加账户")


if __name__ == "__main__":
    fix_account_config_path()